package org.mtmi.ui.controls.edits;

import java.util.Collection;
import java.util.List;

import org.mtmi.ui.IMG;
import org.mtmi.ui.actions.Action;
import org.mtmi.ui.actions.IRetargetableAction;
import org.mtmi.ui.controls.Keyboard;
import org.mtmi.ui.controls.listeners.KeyboardKeyStateEvent;
import org.mtmi.ui.controls.listeners.KeyboardListener;
import org.mtmi.ui.controls.listeners.KeyboardOctaveEvent;
import org.mtmi.ui.drawables.IDrawable;

public class AddKeyboardOctaveAction extends Action implements IRetargetableAction, KeyboardListener
{
	private Object target;
	
	public AddKeyboardOctaveAction( Keyboard k ) {
		super( PUSH );
		setTarget( k );
	}
	
	@Override
	/** @return true if object is an instance of Keyboard or a collection of keyboard instances */
	public boolean isTargetHandled( Object c ) {
		if( c instanceof Keyboard ) return true;
		if( c instanceof Collection ) {
			for( Object o : ((Collection<?>)c) ) {
				if( !(o instanceof Keyboard ) ) return false;
			}
			return true;
		}
		return false;
	}
	
	@Override
	public void setTarget( Object c ) {
		if( target!=null ) {
			if( target instanceof Keyboard ) {
				((Keyboard)target).removeKeyboardListener( this );
			} else {
				for( Object o : (Collection<?>)target ) {
					((Keyboard)o).removeKeyboardListener( this );
				}
			}
		}
		target = c;
		if( target!=null ) {
			//TODO: doiet etre enlevee (removeKL) aussi !! comment pas de dispose dans action()
			if( target instanceof Keyboard ) {
				((Keyboard)target).addKeyboardListener( this );
			} else {
				for( Object o : (Collection<?>)target ) {
					((Keyboard)o).addKeyboardListener( this );
				}
			}
		}
	}
	
	@Override
	public Object getTarget() {
		return target;
	}

	@Override
	public IDrawable getImage() {
		return IMG.GetD( "icons/octave_add.png" );
	}

	@Override
	public boolean isEnabled() {
		if( target instanceof Keyboard ) {
			return isEnabled( (Keyboard)target );
		} else {
			for( Object o : (Collection<?>)target ) {
				if( !isEnabled( (Keyboard)o ) ) { return false ; }
			}
			return true;
		}
	}
	
	protected boolean isEnabled( Keyboard k ) {
		return k!=null && k.getOctaveCount()<10; //10: a choice, must depend ont 0..127 limits ? ( only if it's a music keyboard
	}

	@Override
	public void run() {
		if( target instanceof Keyboard ) {
			run( (Keyboard)target );
		} else {
			for( Object o : (Collection<?>)target ) {
				run( (Keyboard)o );
			}
		}
	}
	
	protected void run( Keyboard k ) {
		k.setOctaveCount( k.getOctaveCount()+1 );
	}

	@Override
	public void keyboardKeyStateChanged(KeyboardKeyStateEvent event) {}

	@Override
	public void keyboardOctaveCountChanged(KeyboardOctaveEvent event) {
		update();
	}
	
	@Override
	public boolean equals(Object obj) {
		return obj!=null && obj.getClass() == getClass();//instanceof will cover subclasses like RemoveKeyboardOctaveAction
	}
}